package com.toman.ui.work.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceEntity;
import com.toman.R;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.Util.ZXingUtil;
import com.toman.camera.Camera;
import com.toman.camera.PreviewImgActivity;
import com.toman.toolbar.ToolBarActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import okhttp3.Request;
import okhttp3.Response;

import static com.toman.Util.DensityUtil.dip2px;

public class DeviceInfActivity extends ToolBarActivity {

    String id;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_no)
    TextView tvTitleNo;
    @BindView(R.id.tv_title2)
    TextView tvTitle2;
    @BindView(R.id.tv_title3)
    TextView tvTitle3;
    @BindView(R.id.tv_title4)
    TextView tvTitle4;
    @BindView(R.id.cv_base)
    CardView cvBase;
    @BindView(R.id.tv_content1)
    TextView tvContent1;
    @BindView(R.id.tv_content2)
    TextView tvContent2;
    @BindView(R.id.tv_content3)
    TextView tvContent3;
    @BindView(R.id.tv_content4)
    TextView tvContent4;
    @BindView(R.id.tv_content5)
    TextView tvContent5;
    @BindView(R.id.tv_content6)
    TextView tvContent6;
    @BindView(R.id.tv_content7)
    TextView tvContent7;
    @BindView(R.id.tv_content8)
    TextView tvContent8;
    @BindView(R.id.tv_content9)
    TextView tvContent9;
    @BindView(R.id.tv_content10)
    TextView tvContent10;
    @BindView(R.id.tv_content11)
    TextView tvContent11;
    @BindView(R.id.ll_cv)
    LinearLayout llCv;
    @BindView(R.id.cv_more)
    CardView cvMore;
    @BindView(R.id.tv_content12)
    TextView tvContent12;
    private String url, text;//当前要保存的图片的url和标题
    private String param;
    private HashMap<String, Camera> cameraHashMap = new HashMap<>();
    String json;
    private Camera camera;
    private String PhotoTitle;
    private String FaceImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_inf);
        ButterKnife.bind(this);
        initHandler();
        initView();
        initToolBar("设备详情");
        get();
    }

    private void initView() {
        id = getIntent().getStringExtra("id");

    }

    public void get() {
        OkHttpUtils
                .get(NewBaseUrl.device_info_get + id)
                .params("token", token)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "设备详情: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            DeviceEntity bean = (DeviceEntity) JSON.parseObject(jsonObj.getString("device"), DeviceEntity.class);
                            tvTitle.setText(bean.getDeviceName());
                            tvTitleNo.setText(bean.getDeviceCode());
                            tvTitle2.setText(bean.getEquipmentCode());
                            tvTitle3.setText(bean.getDeviceTypeName());
                            tvTitle4.setText(bean.getDeviceModeName());
                            tvContent1.setText(bean.getDepartmentName());
                            tvContent2.setText(bean.getBeltlineCode());
                            if (bean.getIncorrectValue()==null){
                                tvContent3.setText("");
                            }
                      else {      tvContent3.setText(bean.getIncorrectValue() + "");}
                            tvContent4.setText(bean.getDevicePower());
//                            利用ascii码对应关系0 A 1 B
                            try {
                                int grade=Integer.valueOf(bean.getImportantGrade());
                                tvContent5.setText((char) ( grade+ 65) + "");
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                            tvContent6.setText(bean.getLocationValue());
                            tvContent7.setText(bean.getProductTime());
                            tvContent8.setText(bean.getInstallTime());
                            tvContent9.setText(bean.getLastMaintenanceTime());
                            tvContent10.setText(bean.getMaintenancePeriod());
                            if (bean.getMaintenanceByRuntime().equals("0")) {
                                tvContent11.setText("是");
                            } else {
                                tvContent11.setText("否");
                            }
tvContent12.setText(bean.getBeltlineName());

                            ArrayList<String> list = new ArrayList<>();
                            JSONObject device = jsonObj.getJSONObject("device");
                            for (int i = 1; i <= 9; i++) {
                                String str = device.getString("image" + i + "Path");
                                if (str == null || str.equals("")) ;
                                else {
                                    list.add(str);
                                }
                            }

                            if (list.size() != 0) {
                                String[] url = new String[list.size()];
                                list.toArray(url);
                                insertURL("图片", url);
//                               createPhoto("图片2",url);
                            }


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    //    插入多图片数组
    public void insertURL(final String text1, final String[] imgurl) {
//        10dp的默认margin
        int margin = dip2px(this, 10);
        int h = dip2px(this, 1);
        int h1 = dip2px(this, 100);
        int h2 = dip2px(this, 30);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
//        获取当前屏幕的宽度
        int width = wm.getDefaultDisplay().getWidth() - 4 * margin;
        int height = wm.getDefaultDisplay().getHeight();
//        计算一个图片所占的宽度
        int left = (width - 4 * margin) / 3;

//图片的父控件相对布rl
        RelativeLayout rl = new RelativeLayout(this);
        rl.setPadding(margin, margin, margin, margin);
//        图片的标题
        TextView tv1 = new TextView(this);
        tv1.setText(text1);
        tv1.setId(R.id.tv_code_title);
        RelativeLayout.LayoutParams rlParams =
                new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams tvParams1 =
                new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
        tvParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, tv1.getId());
        rl.addView(tv1, tvParams1);
//for循环插入不同位置的图片
        for (int j = 0; j < imgurl.length; j++) {
            final int num = j;
//            计算图片在第几层
            int x = (int) Math.floor(j / 3);
//            计算图片在第几个位置
            int y = j % 3;
            ImageView img = new ImageView(this);
            img.setId(R.id.tv_code_img + j);
            Picasso.with(this).load(imgurl[j]).error(R.mipmap.ic_launcher).into(img);
            RelativeLayout.LayoutParams imgParams1 =
                    new RelativeLayout.LayoutParams(
                            h1, h1);
//            img.setScaleType(ImageView.ScaleType.FIT_START);
            img.setScaleType(ImageView.ScaleType.CENTER_CROP);

            imgParams1.addRule(RelativeLayout.BELOW, tv1.getId());
//            设置图片相对父控件的位置
            imgParams1.leftMargin = (y + 1) * margin + y * left;
            imgParams1.topMargin = (x + 2) * margin + x * left;
            //注册上下文菜单
            registerForContextMenu(img);
//            将图片设置到RL父控件中去
            rl.addView(img, imgParams1);
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("imgpath", imgurl[num]);
                    intent.setClass(getApplication(), PreviewImgActivity.class);
                    startActivity(intent);
                }
            });

            img.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
//                    savePhoto(imgurl[num], text1);

                    url = imgurl[num];
                    text = text1;
                    return false;
                }
            });

        }

//        把RL父控件加到总控件ll中去
        llCv.addView(rl, rlParams);
        View view = new View(this);
        view.setBackgroundColor(getResources().getColor(R.color.line_gray));
        RelativeLayout.LayoutParams vParams =
                new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.MATCH_PARENT,
                        h);
        llCv.addView(view, vParams);
    }

    private void savePhoto(String path, final String text1) {
        //                     由于用了帕斯卡的xml加载图片，imageview转换bitmap会失效，所以使用帕斯卡自带的方法
        Picasso.with(getApplicationContext())
                .load(path)
                .into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        ZXingUtil.saveImageToGallery(getApplicationContext(), bitmap, text1);
                        ToastUtil.makeText(getApplicationContext(), "保存成功！");
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
    }

    private void createPhoto(final String title, String[] url) {
        int margin = dip2px(this, 10);
        int etWidth = dip2px(this, 300);
        int h = dip2px(this, 1);
        RelativeLayout rl = new RelativeLayout(this);
        LinearLayout ll = new LinearLayout(this);
        TextView tv1 = new TextView(this);
        tv1.setText(title);
        tv1.setId(R.id.tv_code_title);
        GridLayout gl_camara = new GridLayout(this);
        final Camera camera1 = new Camera(this, gl_camara, true, 9, mHandler, title);
        PhotoTitle = title;
        cameraHashMap.put(title, camera1);
        camera1.showInternet(url);
        gl_camara.requestDisallowInterceptTouchEvent(true);
        gl_camara.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.print("onclick");
                camera = camera1;
                PhotoTitle = title;


            }
        });
        gl_camara.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                ToastUtil.print("ontouch");
                camera = camera1;
                PhotoTitle = title;

                return false;
            }
        });


        tv1.setPadding(margin, margin, margin, margin);


        gl_camara.setPadding(2 * margin, margin, margin, margin);
        llCv.addView(tv1);
        llCv.addView(gl_camara);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(0, 1, 0, "保存图片");

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                savePhoto(url, text);
                break;

        }
        return true;
    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:

                        break;

                    default:
                        break;
                }
            }
        };
    }

}
